import { Request, Response, NextFunction } from "express";
import { errorHandler } from "../utils/handler-utils";
import { uploadDir } from "../utils/storage-utils";
import * as multer from "multer"
import * as path from "path"



const videoFilter = (req, file: Express.Multer.File, cb: multer.FileFilterCallback) => {
  // 文件类型过滤
  const filetypes = /mp4|m4v|avi|mov|mkv/;
  const mimetype = filetypes.test(path.extname(file.originalname).toLowerCase()) ? true : false;
  if (mimetype) {
    cb(null, true);
  } else {
    cb(new Error(`仅支持${filetypes}文件格式，请重新上传`));
  }
};

const imageFilter = (req, file: Express.Multer.File, cb: multer.FileFilterCallback) => {
  // 文件类型过滤
  const filetypes = /jpeg|jpg|png/;
  const mimetype = filetypes.test(path.extname(file.originalname).toLowerCase()) ? true : false;
  if (mimetype) {
    cb(null, true);
  } else {
    cb(new Error(`仅支持${filetypes}文件格式，请重新上传`));
  }
};


// 视频上传
export const videoUpload = multer({
  storage: multer.diskStorage({
    //设置上传后文件路径，uploads文件夹会自动创建。
    destination(req, file, cb) {
      cb(null, uploadDir);
    },
    //给上传文件重命名，获取添加后缀名
    filename(req, file, cb) {
      // 解码文件名
      var fileFormat = (file.originalname).split(".");
      var suffix = fileFormat[fileFormat.length - 1];
      const decodedOriginalName = decodeURIComponent(file.originalname.replace(`.${suffix}`,""));
      // console.log(decodedOriginalName)
      cb(null, decodedOriginalName + '-' + Date.now() + "." + suffix);
      //cb(null, file.fieldname + '-' + Date.now() + "." + suffix);
    },
  }),
  fileFilter: videoFilter,
  // limits: {
  //   fileSize: 1024 * 1024 * 5, // 限制最大图片5MB
  // },
});

// 图片上传
export const imageUpload = multer({
  storage: multer.diskStorage({
    //设置上传后文件路径，uploads文件夹会自动创建。
    destination(req, file, cb) {
      cb(null, uploadDir);
    },
    //给上传文件重命名，获取添加后缀名
    filename(req, file, cb) {
      var fileFormat = (file.originalname).split(".");
      var suffix = fileFormat[fileFormat.length - 1];
      const decodedOriginalName = decodeURIComponent(file.originalname.replace(`.${suffix}`,""));
      // console.log(decodedOriginalName)
      cb(null, decodedOriginalName + '-' + Date.now() + "." + suffix);
      //cb(null, file.fieldname + '-' + Date.now() + "." + suffix);
    },
  }),
  fileFilter: imageFilter,
  // limits: {
  //   fileSize: 1024 * 1024 * 5, // 限制最大图片5MB
  // },
});


// 控制multer中间件上传报错的中间件
export const uploadError = (
  error: Error,
  req: Request,
  res: Response,
  __: NextFunction
) => {
  if (error instanceof multer.MulterError) {
    errorHandler({
      error,
      httpStatus: 400,
      message: `multer.MulterError ${error.message}`,
      req,
      res,
    });
  } else {
    errorHandler({
      error,
      httpStatus: 400,
      message: `中间件 ${error.message}`,
      req,
      res,
    });
  }
};

/**
 * 上传文件 req.file 类型接口
 */
export interface UploadedFile {
  fieldname: string;
  originalname: string;
  encoding: string;
  mimetype: string;
  destination: string;
  filename: string;
  path: string;
  size: number;
}